<?php
namespace app\user2\controller;

use cmf\controller\BaseController;
use app\user2\model\UserModel;

/**
 * 用户模块的API接口
 */
class ApiController extends BaseController
{
    public function __construct()
    {
        config("default_return_type","json");
    }
    public function register()
    {
        $nickname=input("nickname");
        $password=input("password");
        if(!$nickname||!$password){
            $this->error("用户名和密码不能为空");
        }
        $um=new UserModel();
        $user=$um->register($nickname,$password);
        if(!$user){
            $this->error($um->getError());
        }
        $this->result($user);
    }
    public function login()
    {
        $uid=input("user_id");
        $nickname=input("nickname");
        $password=input("password");
        if($uid){
            $where=["id"=>$uid];
        }
        elseif($nickname){
            $where=["nickname"=>$nickname];
        }
        else{
            $this->error("用户id或昵称不能为空");
        }
        if(!$password){
            $this->error("密码不能为空");
        }
        $um=new UserModel();
        $user=$um->login($where,$password);
        if(!$user){
            $this->error($um->getError());
        }
        $this->result($user);
    }
    protected function checkLoginStatus()
    {
        $token=input("token");
        if(!$token){
            $this->error("token不能为空");
        }
        session_id($token);
        $user=session("user");
        if(!$user){
            $this->error("用户未登录");
        }
        return $user;
    }
    public function updateInfo()
    {
        $user=$this->checkLoginStatus();
        $update=[];
        $nickname=input("nickname");
        if($nickname){
            $update["nickname"]=$nickname;
        }
        $um=new UserModel();
        $result = $um->allowField(["nickname"])->isUpdate(true)->save($_REQUEST, ["id"=>$user["id"]]);
        if($result===false){
            $this->error("修改用户信息失败");
        }
        $user=array_merge($user,$update);
        session("user",$user);
        $this->success();
    }
    public function updatePassword()
    {

    }
    public function getBackPassword()
    {

    }
    //删除用户
    public function remove()
    {
        $user=$this->checkLoginStatus();
        $um=new UserModel();
        $result=$um->where(["id"=>$user["id"]])->delete();
        if($result===false){
            $this->error("删除用户失败");
        }
        $this->success();
    }
}